---@class DSStoneDirItem : UIComponentInterface
local DSStoneDirItem = Class("DSActorItem",UIComponentInterface)
local tempVec1 = Vector2.New()
local tempVec2 = Vector2.New()
function DSStoneDirItem:OnCreate(obj)
    ---@type GComponent
    self.fguiObj = obj
    self.ctrlType = self:GetController("Type")
    self.width = self.fguiObj.width
    self.fguiObj.pivotX = 0.5
    self.fguiObj.pivotY = 0.5
    self.fguiObj.pivotAsAnchor = true
    self.defaultRotate = 45
end
function DSStoneDirItem:OnDestroy()
    if self.fguiObj then
        self.fguiObj:Dispose()
        self.fguiObj = nil
        self:DelReferenceAll()
    end
end
function DSStoneDirItem:SetVisible(visible)
    if self.visible ~= visible then
        self.fguiObj.visible = visible
        self.visible = visible
    end
end
---@param actor RedRob.Stone
function DSStoneDirItem:Refresh(actor)
    self.id = actor:GetId()
    self.ctrlType.selectedIndex = actor:GetType()
end

function DSStoneDirItem:SetPos(x,y)
    local actor = RedRob.ActorManager.GetActor(self.id)
    local inScreen = false
    if actor then
        inScreen = RedRob.CameraController.IsPosInScreen(actor:GetPos().x,1)
        if not inScreen then
            local my = RedRob.KeyController:GetCtrl()
            if not my then
                self:SetVisible(false)
                return
            end
            local p = actor:GetPos()
            local x,y,z = RedRob.ClientBattle.LocalToWorld(p.x,p.y,p.z)
            x,y = RedRob.ClientBattle.WorldToScreenPoint(x,y,z)
            x,y = FGUIScreenToLocal(self.fguiObj.parent,x,y)
            --
            p = RedRob.KeyController:GetCtrl():GetPos()
            local px,py,pz = RedRob.ClientBattle.LocalToWorld(p.x,p.y,p.z)
            px,py = RedRob.ClientBattle.WorldToScreenPoint(px,py,pz)
            px,py = FGUIScreenToLocal(self.fguiObj.parent,px,py)
            local sx = x
            local half = self.width/2
            if sx < half then
                sx = half
            elseif sx + half > 1080 then
                sx = 1080 - half
            end
            local xDis = px - x
            local yDis = py - y
            if math.abs(xDis) < 0.0001 then
                self.fguiObj:SetXY(sx,y)
            else
                local sy = (sx - x)/xDis * yDis+y
                self.fguiObj:SetXY(sx,sy)
            end
            tempVec1:Set(0,1)
            tempVec2:Set(x-px,-y+py)
            local angle = Vector2.Angle(tempVec1,tempVec2)
            if px > x then
                angle = -angle
            end
            self.fguiObj.rotation = angle+self.defaultRotate
        end
    end
    self:SetVisible(not inScreen)
end
return DSStoneDirItem